package com.example.volleyball.playcharting.android;

import java.util.concurrent.ExecutionException;

import sharedClasses.*;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.view.Display;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnTouchListener{
	LinearLayout layout1;
	LinearLayout buttonLayout;
	LinearLayout popLayout;
	RelativeLayout resultsLayout;
	ImageView imageView;
	TextView key1;
	TextView key2;
	TextView key3;
	TextView key4;
	TextView scoreText;
	float x1=0;
	float x2;
	float y1=0;
	float y2;
	float cLeft;
	float cRight;
	float cBottom;
	float cTop;
	int scoreHome,scoreAway = 0;
	int rotation = 1;
	int lastPoint = 0;
	int playCount =0;
	Button viewButton;
	Button newButton;
	Button quickButton;
	Button detailButton;
	Button infoButton;
	Button clearButton;
	Button addPlay;
	Button doneButton;
	RadioGroup point;
	RadioButton homeRadio;
	Bitmap bitmap;
	Canvas c;
	Paint p;
	Play currentPlay;
	Match match;
	Rect court;
	Rect[] zones=new Rect[12];
	Client client;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        Intent intent = getIntent();
        setContentView(R.layout.test);
        currentPlay = new Play();
        currentPlay.Rotation = rotation;
        match = new Match();
		MessageTask mess = new MessageTask();
		mess.execute(match);
        scoreText = (TextView)this.findViewById(R.id.score_text);
        buttonLayout=(LinearLayout)this.findViewById(R.id.buttonLayout);
        popLayout=(LinearLayout)this.findViewById(R.id.pop_up);
        popLayout.setVisibility(View.INVISIBLE);
        resultsLayout=(RelativeLayout)findViewById(R.id.results_layout);
        resultsLayout.setVisibility(View.INVISIBLE);
        buttonLayout.bringToFront();
        imageView = (ImageView)this.findViewById(R.id.imageView1);
        imageView.setOnTouchListener(this);
        imageView.setClickable(false);
        
        key1 = (TextView)findViewById(R.id.textView5);
        key2 = (TextView)findViewById(R.id.textView6);
        key3 = (TextView)findViewById(R.id.textView7);
        key4 = (TextView)findViewById(R.id.textView8);
        key1.setTextColor(Color.parseColor("#FF6600"));
        key2.setTextColor(Color.MAGENTA);
        key3.setTextColor(Color.BLUE);
        key4.setTextColor(Color.parseColor("#336600"));
        key4.setVisibility(View.GONE);
        drawBlankCourt();

        clearButton=(Button)findViewById(R.id.clearButton);
        clearButton.setVisibility(View.INVISIBLE);
        clearButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
			  if(imageView.isClickable()){
				  currentPlay = new Play();
				  x1=0;
				  y1=0;
				  playCount=0;
				  drawBlankCourt();
			  }
			}     	
        });
        newButton=(Button)findViewById(R.id.newButton);
        newButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(imageView.isClickable()){
					imageView.setClickable(false);
					newButton.setText("New");
					popLayout.setVisibility(View.VISIBLE);
			        popLayout.bringToFront();
				    clearButton.setVisibility(View.INVISIBLE);
				}
				else{
				  imageView.setClickable(true);
				  resultsLayout.setVisibility(View.INVISIBLE);
				  drawBlankCourt();
				  quickButton.setVisibility(View.INVISIBLE);
				  newButton.setText("Play Complete");
				  clearButton.setVisibility(View.VISIBLE);
				}
			}     	
        });
        doneButton=(Button)findViewById(R.id.doneButton);
        doneButton.setOnClickListener(new OnClickListener(){
        	public void onClick(View v){
        		resultsLayout.setVisibility(View.INVISIBLE);
        		newButton.setVisibility(View.VISIBLE);
        		scoreText.setVisibility(View.VISIBLE);
        		drawBlankCourt();
        	}
        });
        quickButton=(Button)findViewById(R.id.quickButton);
        quickButton.setVisibility(View.INVISIBLE);
        quickButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(quickButton.getText().equals("Quick Analysis")){
				  quickButton.setText("Sent");
				  resultsLayout.setVisibility(View.VISIBLE);
				  newButton.setVisibility(View.INVISIBLE);
				  scoreText.setVisibility(View.INVISIBLE);
				  quickButton.setVisibility(View.INVISIBLE);
				  QuickAnalysisTask mess = new QuickAnalysisTask();
				  Play[] patterns;
			  	  mess.execute();
			  	  int[] colors = {Color.parseColor("#FF6600"),Color.MAGENTA,Color.BLUE, Color.parseColor("#336600")};
			      Paint paint = new Paint();
				  paint.setStyle(Style.STROKE);
			      paint.setStrokeWidth(4);
				  TextView[] keys = {key1, key2, key3, key4};
				  try
				  {
					  patterns = mess.get();
					  //TODO DISPLAY THIS
					  for(int i=0;i<patterns.length;i++){
						  if (patterns[i] != null)
						  {
							  keys[i].setVisibility(View.VISIBLE);
							  for(int j=0;j<patterns[i].Children.size();j++){
							    Action act = patterns[i].Children.get(j);
							    int[] origin = BEUIConverter.convertBEtoUI(act.getOrigin());
							    int[] destination = BEUIConverter.convertBEtoUI(act.getDestination());
							    paint.setStyle(Style.FILL);
							    if(j==0){
							      paint.setColor(Color.GREEN);
							      c.drawCircle(cLeft+(origin[0])*20, cTop+(origin[1])*20,8,paint);
							    }
							    if(j==patterns[i].Children.size()-1){
							      paint.setColor(Color.RED);
							      c.drawCircle(cLeft+(destination[0])*20, cTop+(destination[1])*20,8,paint);
							    }
							    paint.setStyle(Style.STROKE);
							    paint.setColor(colors[i]);
							    c.drawLine(cLeft+(0+origin[0])*20, cTop+(0+origin[1])*20, 20*(destination[0]+0)+cLeft, 20*(0+destination[1])+cTop, paint);
							    System.err.println("(" + origin[0] + ", " + origin[1] + ") --> (" + destination[0] + ", " + destination[1] + ")");
							    imageView.invalidate();
							  }
						  }
						  else
							  keys[i].setVisibility(View.GONE);
					  }
				  }  
				  catch (InterruptedException e)
				  {
					  // TODO Auto-generated catch block
					  e.printStackTrace();
				  }
				  catch (ExecutionException e)
				  {
					  // TODO Auto-generated catch block
					  e.printStackTrace();
				  }
			  }
			}
        });
        point = (RadioGroup)findViewById(R.id.point_to);
        homeRadio = (RadioButton)findViewById(R.id.home_choice);
        addPlay=(Button)findViewById(R.id.add_play);
        addPlay.setOnClickListener(new OnClickListener(){
        	public void onClick(View v){
        		if(currentPlay.getChildren().size()>0){
        			if(homeRadio.isChecked()){
        		    	currentPlay.getChildren().get(playCount-1).setResult(1);
        		    	scoreHome++;
        				if (lastPoint == 1)
        				{
        					rotation++;
        					rotation = rotation % 6;
        					if (rotation == 0)
        					{
        						rotation = 6; //because 0 doesn't mean anything to us
        					}
        				}
        				lastPoint = 0;
        			}
        			else{
        				currentPlay.getChildren().get(playCount-1).setResult(-1);
        				scoreAway++;
        				lastPoint = 1;
        			}
        			scoreText.setText("Score: "+scoreHome+" - "+ scoreAway);
        			match.addPlay(currentPlay);
        			AddPlayTask mess = new AddPlayTask();
        			mess.execute(currentPlay);
        		}
        		else{
        			Toast.makeText(MainActivity.this, "You must enter a play sequence first", Toast.LENGTH_SHORT);
        		}
        		currentPlay = new Play();
        		x1=0;
        		y1=0;
        		playCount=0;
        		currentPlay.Rotation = rotation;
        		popLayout.setVisibility(View.INVISIBLE);
        		drawBlankCourt();
        		quickButton.setVisibility(View.VISIBLE);
        		quickButton.setText("Quick Analysis");
        	}
        });
  
        
    }
    private void drawBlankCourt(){
    	 Display currentDisplay = getWindowManager().getDefaultDisplay();
    	  p = new Paint();
          p.setColor(Color.BLACK);
          p.setStyle(Style.STROKE);
          p.setStrokeWidth(4);         
          float dw = currentDisplay.getWidth();
          float dh = currentDisplay.getHeight();
          int scale = 20;      
          cLeft=(dw-(scale*60))/2;
          cRight=(dw-cLeft);
          cTop=10;
          cBottom=cTop+(scale*30);
          int zoneH=(int) ((cBottom-cTop)/3);
          int zoneW=(int) ((cRight-cLeft)/4);
          int count =0;         
          bitmap = Bitmap.createBitmap((int) dw, (int) dh, Bitmap.Config.ARGB_8888);
          c= new Canvas(bitmap);
          c.drawLine(cLeft+(cRight-cLeft)/2, cTop, cLeft+(cRight-cLeft)/2, cBottom, p);
          p.setColor(Color.GRAY);
          p.setStrokeWidth(2);
          for(int i=0;i<4;i++){
          	for(int j=0;j<3;j++){
          		zones[count]=new Rect();
          	  zones[count].set((int)cLeft+(i*zoneW),(int)cTop+(j+1)*zoneH,(int)cLeft+(i+1)*zoneW,(int)cTop+(j*zoneH));
          	  c.drawRect(zones[count], p);
          	  count++;
          	}
          }
          p.setColor(Color.BLACK);
          p.setStyle(Style.STROKE);
          p.setStrokeWidth(4);      
          court= new Rect();
          court.set((int)cLeft,(int)cBottom,(int)cRight,(int)cTop);
          c.drawRect(court, p);
          imageView.setImageBitmap(bitmap);
    }
  

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
   


	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
  	  int act = event.getAction();
  	  if(v.isClickable()){
  		  if(act==MotionEvent.ACTION_UP){
  			  x2=event.getX();
  			  y2=event.getY();
  			  p.setStyle(Paint.Style.FILL);
  			  p.setColor(Color.rgb(0, 94, 189));
  			  x2=adjustX(x2);
  			  y2=adjustY(y2);
  			  c.drawCircle(x2, y2, 10, p);
  			  c.drawPoint(x2, y2, p);
  		  
  			  if(x1!=0 && y1!=0){
  				  p.setStyle(Paint.Style.STROKE);
  				  p.setColor(Color.rgb(0, 128, 64));
  				  c.drawLine(x1,y1,x2,y2,p);
  				  int xscaled = (int)(x1-cLeft)/20;
  				  int yscaled = (int)(y1-cTop)/20;
  				  int x2scaled = (int)(x2-cLeft)/20;
  				  int y2scaled = (int)(y2-cTop)/20;
  				  int[] scaled = BEUIConverter.convertUItoBE(xscaled,yscaled);
  				  int[] scaled2 = BEUIConverter.convertUItoBE(x2scaled,y2scaled);			  
  				  Action action = new Action(scaled,scaled2,-1);
  				  currentPlay.addAction(action);
  				  playCount++;
  			  }
  		    x1=x2;
  		    y1=y2;
  		    imageView.invalidate();
  		  }
		  return true;
  	  }
  	  return false;
	}
	private float adjustX(float x){
		if(x<cLeft)
			x=cLeft;
		if(x>=cRight)
			x=cRight-1;
		return x;
	}
	private float adjustY(float y){
		if(y<cTop)
			y=cTop;
		if(y>=cBottom)
			y=cBottom-1;
		return y;
	}
}
